package com.ngmaster.socket.connection;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * tcp 链接
 * */
public class TcpConnection extends NetConnection<ChannelHandlerContext> {
	
	/**
	 * 初始化
	 * @param connectionId
	 * @param channelContext
	 */
	@Override
	public void init(long connectionId, ChannelHandlerContext channelContext, Object object) {
		super.init(connectionId, channelContext, object);
		String ip = getClientIp();
		setConnectionIp(ip);
	}

	@Override
	public String getClientIp() {
		String sAddress  = channelHandlerContext.channel().remoteAddress().toString();
		String[] str  = sAddress.toString().split(":");
		String ip = str[0].split("/")[1];
		return ip;
	}
	
	@Override
	public void sendMessage(ByteBuf byteBuf) {
		if (this.getChannelHandlerContext() == null) {
			return;
		}
		this.getChannelHandlerContext().writeAndFlush(byteBuf);
	}

	@Override
	public void close() {
		this.getChannelHandlerContext().close();
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder("TcpConnection{");
		sb.append("connectionId=").append(connectionId);
		sb.append(", channelHandlerContext=").append(channelHandlerContext);
		sb.append(", isWaitIng=").append(isWaitIng);
		sb.append(", clientObject=").append(clientObject);
		sb.append(", connectionIp='").append(connectionIp).append('\'');
		sb.append('}');
		return sb.toString();
	}
}
